﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers.QandA
{
    [Description("字典")]
    public class DictionaryController : BaseController
    {
        public IDictionaryContract DictionaryContract { get; set; }
        #region 列表
        [Description("字典-列表")]
        public ActionResult Index()
        {
            return View();
        } 
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "", string type = "")
        {
            var query = DictionaryContract.Entities;
            if (type != "" && type != "全部")
            {
                query = query.Where(m => m.Name == type);
            }
            if (search !="")
            {
                query = query.Where(m=>m.Name.Contains(search));
            }
            var total = query.Count();
            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<Dictionary>().AsQueryable();

            //此处可以采用匿名对象 GridData<object> 
            GridData<Dictionary> gridData = new GridData<Dictionary>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss"); 
        } 
        #endregion

        #region 名称添加
        [Description("字典-名称添加")]
        public ActionResult InsertName()
        {
            return View();
        }
        [HttpPost]
        public ActionResult InsertNameAsync(Dictionary entity)
        {
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.Value == null)
            {
                entity.Value = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = DictionaryContract.CheckExists(m => m.Name.Equals(entity.Name));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的名称";
                }
                else
                {
                    var count = DictionaryContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 名称编辑
        [Description("字典-名称编辑")]
        public ActionResult EditName(string name)
        { 
            ViewData["entity"] = name;
            return View();
        }
        [HttpPost]
        public ActionResult EditNameAsync(Dictionary entity)
        {
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.Value == null)
            {
                entity.Value = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            var result = new AjaxResult();
            try
            { 
                var LastName = entity.Value;
                var NewName = entity.Name;
                var query = DictionaryContract.Entities.Where(m=>m.Name == LastName).ToList(); 
                for (int i=0;i<query.Count();i++)
                { 
                    var idsInt = query[i].Id.ToString();
                    DictionaryContract.UpdateDirect(n => idsInt.Contains(n.Id.ToString()), N=> new Dictionary { Name = NewName });
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 名称删除
        [Description("字典-名称删除")]
        [HttpPost]
        public ActionResult DeleteNameAsync(string name)
        {
            var result = new AjaxResult();
            try
            {
                var query = DictionaryContract.Entities.Where(m => m.Name==name).ToList();
                for (int i = 0; i < query.Count(); i++)
                {
                    var idsInt = query[i].Id.ToString();
                    DictionaryContract.DeleteDirect(Convert.ToInt32(idsInt));
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                } 

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 

        #region 值添加
        [Description("字典-值添加")]
        public ActionResult InsertValue(string name)
        { 
            ViewData["entity"] = name;
            return View();
        }
        [HttpPost]
        public ActionResult InsertValueAsync(Dictionary entity)
        {
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.Value == null)
            {
                entity.Value = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = DictionaryContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Value.Equals(entity.Value));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的值";
                }
                else
                {
                    var count = DictionaryContract.Insert(entity);
                    var selectName = DictionaryContract.Entities.Where(m=>m.Name==entity.Name).ToList();
                    for (int i = 0;i< selectName.Count();i++)
                    {
                        var Id = selectName[i].Id;
                        var selectId = DictionaryContract.GetByKey(Id);
                        if (selectId.Value == ""|| selectId.Value==null)
                        {
                            DictionaryContract.DeleteDirect(Id);
                        }
                    }

                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 值修改
        [Description("百问百答-问题修改")]
        public ActionResult EditValue(int id)
        {
            var entity = DictionaryContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体"); 
            ViewData["entity"] = entity; 
            return View();
        }
        [HttpPost]
        public ActionResult EditValueAsync(Dictionary entity)
        {
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.Value == null)
            {
                entity.Value = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            var result = new AjaxResult();
            try
            {
                var query = DictionaryContract.CheckExists(m => m.Value.Equals(entity.Value) && m.Value.Equals(entity.Value) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的值";
                }
                else
                {
                    var count = DictionaryContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 值删除
        [Description("百问百答-问题删除")]
        [HttpPost]
        public ActionResult DeleteValueAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                for (int i = 0;i<idsInt.Length;i++)
                {
                    DictionaryContract.DeleteDirect(idsInt[i]);
                }

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 分类树
        [Description("字典-树")]
        public ActionResult CmpTreeAsync()
        { 
            var query = (from d in DictionaryContract.Entities
                         group d by d.Name into g
                         select new
                         {
                             text = g.Key,
                             id=g.Key
                         }).ToList();
            return JsonEx(new
            {
                id = "0",
                text = "全部",
                children = query
            });
        }
        #endregion
    }
}